<?php
class DB{
	static protected $link;
	/**
	 * DB constructor.
	 * @param $config
	 */
    private function __construct(){
        $this->link = new PDO("mysql:host=redis.mfssl.com;dbname=root","ultrax","123456");
		$this->link->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	}
	/**
	 * @return DB|PDO
	 */
	static public function getInstance(){
		if(self::$link){
			return self::$link;
		}else{
			self::$link = new self();
			return self::$link;
		}
	}
	/*数据库关闭*/
	public function close(){
		$this->link = null;
	}

	/**
	 * @param $sql
	 * @return array 查询所有数据记录值
	 */
	public function query($sql){
		$this->link->exec("set names utf8");
		$res = $this->link->query($sql);
		$list = $res->fetchAll(PDO::FETCH_ASSOC);
		return $list;
	}
	/**
	 * @param $sql
	 * @return mixed 查询1条记录值
	 */
	public function first($sql){
		$this->link->exec("set names utf8");
		$result = $this->link->query($sql);
		$result->setFetchMode(PDO::FETCH_ASSOC);
		$list = $result->fetch();
		return $list;
	}
	/**
	 * @param $sql
	 * @return int 仅限于新增记录条数 1条
	 */
	public function insert($sql){
		$this->link->exec("set names utf8");
		$this->link->exec($sql);
		$num = $this->link->lastInsertId();
		return $num;
	}
	/**
	 * @param $sql
	 * @param array $list
	 * @return int 仅限新增记录条数大于1条
	 */
	public function Insert_list($sql,$list=array()){
		$stmt = $this->link->prepare($sql);
		$num = 0;
		foreach($list as $data){
			$stmt->execute($data);
			$num+=$stmt->rowCount();
		}
		return $num;
	}
	/**
	 * @param $sql
	 * @return int 更新数据库记录
	 */
	public function update($sql){
		$num = $this->link->exec($sql);
		return $num;
	}
	/**
	 * @param $sql
	 * @return int 删除数据记录
	 */
	public function delete($sql){
		$num = $this->link->exec($sql);
		return $num;
	}
}